package com.interview.one.controller;

import com.interview.one.common.BusinessException;
import com.interview.one.common.CommonRes;
import com.interview.one.common.EmBusinessError;
import com.interview.one.domain.GetGoodsDetailReq;
import com.interview.one.domain.GetGoodsListByKeywordReq;
import com.interview.one.domain.GetGoodsListReq;
import com.interview.one.model.GoodsInfo;
import com.interview.one.model.GoodsSku;
import com.interview.one.service.GoodsService;
import com.interview.one.utils.YuanFenConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @PostMapping("/getGoodsList")
    public CommonRes getGoodsList(@RequestBody GetGoodsListReq req) throws BusinessException {

        List<GoodsInfo> list = this.goodsService.getGoodsList(req.getCategoryId(), req.getPageNo());
        if ((list == null) || (list.size() == 0)) {
            throw new BusinessException(EmBusinessError.NO_DATA_ERROR);
        }

        for (GoodsInfo info : list) {
            info.setGoodsDefaultPrice(YuanFenConverter.changeY2F(info.getGoodsDefaultPrice()));
            info.setMaxPage(this.goodsService.getAllGoodsList(req.getCategoryId()).size() / 6 + 1);
        }
        return CommonRes.create(list);
    }

    @PostMapping("/getGoodsDetail")
    public CommonRes getGoodsDetail(@RequestBody GetGoodsDetailReq req) throws BusinessException {
        GoodsInfo goodsInfo = this.goodsService.getGoodsDetail(req.getGoodsId());
        if (goodsInfo == null) {
            throw new BusinessException(EmBusinessError.NO_DATA_ERROR);
        }

        goodsInfo.setGoodsDefaultPrice(YuanFenConverter.changeY2F(goodsInfo.getGoodsDefaultPrice()));

        List<GoodsSku> skuList = this.goodsService.getGoodsSkuList(goodsInfo.getId());
        for (GoodsSku sku : skuList) {
            sku.setSkuTitle(sku.getGoodsSkuTitle());
            sku.setSkuContent(Arrays.asList(sku.getGoodsSkuContent().split(",")));
        }
        goodsInfo.setGoodsSku(skuList);
        return CommonRes.create(goodsInfo);
    }

    @PostMapping("/getGoodsListByKeyword")
    public CommonRes getGoodsListByKeyword(@RequestBody GetGoodsListByKeywordReq req) throws BusinessException {
        List<GoodsInfo> list = this.goodsService.getGoodsListByKeyword(req.getKeyword(), req.getPageNo());
        if ((list == null) || (list.size() == 0)) {
            throw new BusinessException(EmBusinessError.NO_DATA_ERROR);
        }

        for (GoodsInfo info : list) {
            info.setGoodsDefaultPrice(YuanFenConverter.changeY2F(info.getGoodsDefaultPrice()));
            info.setMaxPage(this.goodsService.getAllByKeyword(req.getKeyword()).size() / 6 + 1);
        }
        return CommonRes.create(list);
    }
}
